define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goodshandle/goods/index',
                    add_url: 'goodshandle/goods/add',
                    edit_url: 'goodshandle/goods/edit',
                    del_url: 'goodshandle/goods/del',
                    multi_url: 'goodshandle/goods/multi',
                    table: 'goods',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'category_id', title: __('Category_id')},
                        {field: 'name', title: __('Name'),cellStyle: function () {return {css: {"min-width": "200px"}}}},
                        {field: 'store_count', title: __('Store_count')},
                        {field: 'market_price', title: __('Market_price'), operate:'BETWEEN'},
                        {field: 'shop_price', title: __('Shop_price'), operate:'BETWEEN'},
                        {field: 'exchange_integral', title: __('Exchange_integral')},
                        {field: 'image', title: __('Image'), formatter: Table.api.formatter.image},
                        {field: 'images', title: __('Images'), formatter: Table.api.formatter.images},
                        {field: 'weigh', title: __('Weigh')},
                        {field: 'give_integral', title: __('Give_integral')},
                        {field: 'sales_sum', title: __('Sales_sum')},
                        {field: 'prom_type', title: __('Prom_type'), visible:false, searchList: {"0":__('Prom_type 0'),"1":__('Prom_type 1'),"2":__('Prom_type 2'),"3":__('Prom_type 3'),"4":__('Prom_type 4')}},
                        {field: 'prom_type_text', title: __('Prom_type'), operate:false},
                        {field: 'prom_id', title: __('Prom_id')},
                        {field: 'status', title: __('Status'), visible:false, searchList: {"0":__('Status 0'),"1":__('Status 1')}},
                        {field: 'status_text', title: __('Status'), operate:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, 
                            buttons: [
                                {name: 'detail', title: __('详情'), classname: 'btn btn-xs btn-primary btn-dialog', icon: 'fa fa-list', url: 'goodshandle/goods/detail', callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }},
                                
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });



            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {


            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                $(document).ready(function(){
                    // alert($('#c-attr_id').val());
                    var isdialog = Config.isdialog.data;

                    // console.log(isdialog);
                    if( isdialog !== false){
                        var row = Config.row.data;
                        var category_id = row.category_id;
                        if(category_id){
                            getAttrData(category_id);
                        }
                    }else{

                    }


                });

                $(document).on("change","#c-category_id", function(){
                    var category_id = $(this).val();

                    getAttrData(category_id);

                }); 

                $(document).on("change","#c-attr_id", function(){
                    var attr_id = $(this).val();

                    getAttrValues(attr_id);
                });

                //规格
                function getAttrData(category_id){
                    
                    var isdialog = Config.isdialog.data;
                    var row = Config.row.data;
                    var attrId = Config.goodsattrData.data;
                    // console.log(attrId);
                    $.ajax({
                        url: "/admin/goodshandle/goods/getAttrData",
                        type: 'get',
                        dataType: 'json',
                        async: true,
                        data: {category_id: category_id},
                        success: function (ret) {

                            var html = '';
                            $.each(ret.data,function(k,v){

                                if(isdialog !== false){

                                    var goodsattr = Config.goodsattr.data;
                                    
                                    if(attrId == v.id){
                                        getAttrValues(v.id,goodsattr);
                                        html += "<option value='"+v.id+"' selected >"+v.name+"</option>";
                                    }else{
                                        getAttrValues(v.id,goodsattr);
                                        html += "<option value='"+v.id+"' >"+v.name+"</option>";
                                    }
 
                                }else{
                                    html += "<option value='"+v.id+"'>"+v.name+"</option>";

                                    if(k == 0){
                                        
                                        getAttrValues(v.id);
                                        
                                    }
                                    
                                }
                                
                            });

                            $('#c-attr_id').html(html);
     
                        }, error: function (e) {
                            Backend.api.toastr.error(e.message);
                        }
                    });
                }

                //规格值
                function getAttrValues(attr_id,goodsattr=''){
                    // console.log(goodsattr);
                    $.ajax({
                        url: '/admin/goodshandle/goods/getAttrInfo',
                        type: 'get',
                        dataType: 'json',
                        data: {attr_id:attr_id},
                        success: function(ret){
                            // console.log(ret);
                            var html = '';
                            if(goodsattr){
                                
                                $.each(ret.data,function(k,v){
                                    // console.log(v);
                                    if(isInArray(goodsattr,v)){
                                        html +='<label for="attr_values[]-'+k+'"><input id="attr_values[]-'+k+'" name="attr_values[]" type="checkbox" value="'+v+'" checked="checked"/> '+v+'</label>';
                                     
                                    }else{
                                        html +='<label for="attr_values[]-'+k+'"><input id="attr_values[]-'+k+'" name="attr_values[]" type="checkbox" value="'+v+'" /> '+v+'</label>';
                                     
                                    }
                                    
                                    
                                });
                            }else{
                                $.each(ret.data,function(k,v){
                                
                                    html +='<label for="attr_values[]-'+k+'"><input id="attr_values[]-'+k+'" name="attr_values[]" type="checkbox" value="'+v+'" /> '+v+'</label>';
                                });

                            }
                            

                            $('#checkbox-values').html(html);

                        }
                    });
                }

                /**
                 * 使用循环的方式判断一个元素是否存在于一个数组中
                 * @param {Object} arr 数组
                 * @param {Object} value 元素值
                 */
                function isInArray(arr,value){
                    for(var i = 0; i < arr.length; i++){
                        if(value === arr[i]){
                            return true;
                        }
                    }
                    return false;
                }

                
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});